#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>

class TcpClient
{
private:
    int _sock;
    std::string _ip;
    uint16_t _port;
public:
    TcpClient(std::string ip,uint16_t port):_sock(-1),_ip(ip),_port(port)
    {}

    void initClient()
    {
        _sock = socket(AF_INET,SOCK_STREAM,0);
        if(_sock < 0)
        {
            std::cout << "socket error" << std::endl;
            exit(1);
        }

        struct sockaddr_in server;
        bzero(&server,0);
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_ip.c_str());

        if(connect(_sock,(struct sockaddr*)&server,sizeof(server)) < 0)
        {
            std::cout << "connect error" << std::endl;
            exit(3);
        }
        std::cout << "connect success" << std::endl;

    }

    void start()
    {
        std::string line;
        while(true)
        {
            std::cout << "请输入# ";
            std::getline(std::cin,line);

            send(_sock,line.c_str(),line.size(),0);
            char buffer[1024];
            ssize_t s = recv(_sock,buffer,sizeof(buffer)-1,0);
            if(s > 0)
            {
                buffer[s] = 0;
                std::cout << "server# " << buffer << std::endl;
            }
            else if(s == 0)
            {
                break;
            }
            else
            {
                break;
            }
        }
        close(_sock);
    }

    ~TcpClient()
    {

    }
};